<template>
    <!-- table的组件封装 -->
    <div class="tableBox">
        
        <vxe-table
            :class="!isOrder?'noOrder':''"
            :empty-text="$t('common.noData')"
            stripe
            style="width: 100%;flex:1;"
            :ref="tableRef"
            border
            show-overflow
            show-header-overflow
            height="100%"
            min-height="200"
            :scroll-y="{enabled: true}"
            :data="tableData"
            :menu-config="menuConfig"
            @menu-click="contextMenuClickEvent"
            @header-cell-menu="openHeaderOperate"
            @cell-menu="openCellOperate"
            :column-config="{resizable: true}"
            @resizable-change="resizableChange"
            :show-footer="showFooter"
            :footer-method="footerMethod"
            :key="key"
            v-bind="gridOptions"
            @current-change="currentChangeEvent"
            @cell-click="checkBoxChangeEvent"
            @checkbox-change="checkChange"
            @checkbox-all="checkBoxAll"
            :row-class-name="tableRowClassName"
            @cell-dblclick="cellDblclick"
            :header-cell-class-name="headerCellClass"
            >
            <vxe-column
                v-for="(config, index) in tableColumnCopy"
                :key="index"
                :type="config.type"
                :field="config.prop"
                :title="config.label"
                :fixed="config.fixed"
                :width="config.width+20"
                :filters="config.filters"
                >
                <template slot-scope="scope">
                    <slot name="content" :row="scope.row" :config="config"></slot>
                </template>
                <template v-if="!config.type&&isOrder" slot="header">
                    <span>{{ config.label }}</span>
                        <span v-if="config.hasOwnProperty('order')" class="custom-sort">
                            <i @click="sortClick(config,'asc',index)" :class="'asc-'+index" class="el-icon-caret-top order-btn"></i>
                            <i @click="sortClick(config,'desc',index)" :class="'desc-'+index" class="el-icon-caret-bottom order-btn"></i>
                        </span>
                </template>
            </vxe-column>
        </vxe-table>
        <HeaderOperate
            ref="HeaderOperate"
            v-if="menuVisible"
            @fooHeader="fooHeader"
            :tableColumn="tableColumn"
        ></HeaderOperate>
        <CellOperate
            ref="CellOperate"
            v-if="cellVisible"
            @fooCell="fooCell"
            @sendCell="sendCell"
        ></CellOperate>
    </div>
</template>

<script>
import HeaderOperate from '@/components/common/HeaderOperate';
import CellOperate from '@/components/common/CellOperate';
import { Sortable } from 'sortablejs';
export default {
  components: {
    HeaderOperate,
    CellOperate
  },
    name: "MyTable",
    props:{
        isOrder:{//是否排序
            type:Boolean,
            default:true
        },
        CellOptionsArr:{//右击单元格数据项组
            type:Array,
        },
        gridOptions: {//是否多选
            type:Object,
            default:function (){
                return {rowConfig:{isCurrent: true, isHover: true},}
            }
        },
        tableColumn: {//表头组
            type: Array
        },
        menuConfig: {//右击菜单
            type:Object,
            default:function (){
                return {header:true}
            }
        },
        // tableColumn参数
        // type  列的类型 seq序号  checkbox复选框  radio单选框  expand展开行
        // fixed 列固定   left（固定左侧）, right（固定右侧）
        // checked:true,右击操作是否显示该列，不写则无法操作
        // key: 4, 唯一值
        // prop: 'sex', 列字段
        // label: 'Sex', 列名称
        // width: 200, 列宽
        // filters: [{ value: '1', label: '男' }] 筛选
        // order:''是否可以排序，不写则无法操作
        tableData: {//表数据
            type: Array
        },
        showFooter:{//是否显示表尾
            type:Boolean,
            default:false
        },
        footerData: {//表尾数据
            type: Array
        },
        tableRef:{//ref名称
            type:String,
            default:'tableRef'
        },
        rowClassNameFunc:{//rou加class类名
            type:Function,
        }
    },
    data() {
        return {
            cellVisible:false,
            menuVisible:false,
            tableColumnCopy:[],
            key:1
        };
    },
    computed:{
    },
    watch: {
        tableColumn:{
            handler:function(){
                this.setTableColumnCopy()
            },
            deep:true
        },
    },
    mounted(){
        this.setTableColumnCopy()
        // 阻止默认行为
        document.body.ondrop = function (event) {
        event.preventDefault();
        event.stopPropagation();
        };
        this.columnDrop();//列拖拽
    },
    methods: {
        headerCellClass(obj){
            if(this.tableColumn[obj.columnIndex].order===undefined){
                return 'noOrder'
            }
        },
        // 单击选中
        currentChangeEvent(obj) {
            this.$emit('sendCurrentData',obj.row)
        },
        tableRowClassName ({ row, rowIndex }) {
            // 把每一行的索引放进row
            row.index = rowIndex

            if(!!this.rowClassNameFunc){
                let className=this.rowClassNameFunc(row)
                return className
            }
        },
        cellDblclick (obj) {
            this.$emit('cellDblclick',obj)
        },
        contextMenuClickEvent (obj) {
            this.$emit('contextMenuClickEvent',obj)
        },
        // 点击单元格
        checkBoxChangeEvent (obj) {
            let isCheck=true  //该单元格所在行能否勾选
            if(!!this.gridOptions.checkboxConfig&&!!this.gridOptions.checkboxConfig.checkMethod){
                isCheck=this.gridOptions.checkboxConfig.checkMethod({row:obj.row})
            }
            if(isCheck){
                // 复选框勾选
                if(!!this.tableColumnCopy[obj.$columnIndex].templateType){
                    this.$refs[this.tableRef].setCheckboxRow([obj.row],true)
                }
                // let sendData=obj.data.filter(item=>{return item.checked})
                // this.$emit('sendCheckBoxList',sendData)
                // console.log(333,sendData)
                // 唤起输入框
                let index = obj.row.index
                let label = obj.column.title
                this.$emit('sendTabClick',{index,label})
            }
        },
        checkChange(obj){
            console.log(obj)
            let isCheck=true  //该单元格所在行能否勾选
            if(!!this.gridOptions.checkboxConfig&&!!this.gridOptions.checkboxConfig.checkMethod){
                isCheck=this.gridOptions.checkboxConfig.checkMethod({row:obj.row})
            }
            if(isCheck){
                // 复选框勾选
                if(!!this.tableColumnCopy[obj.$columnIndex].templateType){
                    this.$refs[this.tableRef].setCheckboxRow([obj.row],true)
                }else{
                    this.$emit('sendCheckBoxList',obj.records)
                }
            }
        },
        // 复选框全选
        checkBoxAll(obj){
            let sendData=obj.records
            this.$emit('sendCheckBoxList',sendData)
        },
        setTableColumnCopy(){
            this.tableColumnCopy=[]
            this.$nextTick(() => {
                this.tableColumnCopy = this.tableColumn.filter((item) => {
                    return item.checked||!item.hasOwnProperty('checked');
                });
            });
        },
        //拖拽列宽对表头组赋值
        resizableChange(data){
            let index=this.tableColumn.findIndex(item=>{return item.prop==data.column.property})
            this.tableColumn[index].width=data.column.renderWidth
        },
        openHeaderOperate({$event}){
            // 阻止右键默认行为
            $event.preventDefault();
            this.menuVisible=true
            this.$nextTick(() => {
                this.$refs.HeaderOperate.init($event);
            });
        },
        fooHeader() {
            // 取消鼠标监听事件 菜单栏
            this.menuVisible = false;
            document.removeEventListener("click", this.fooHeader);
            document.removeEventListener("mousedown", this.fooHeader);
        },
        openCellOperate({$event}){
            if(!this.CellOptionsArr){
                return
            }
            // 阻止右键默认行为
            $event.preventDefault();
            this.cellVisible=true
            this.$nextTick(() => {
                this.$refs.CellOperate.init($event,this.CellOptionsArr);
            });
        },
        fooCell() {
            // 取消鼠标监听事件 菜单栏
            this.cellVisible = false;
            document.removeEventListener("click", this.fooCell);
            document.removeEventListener("mousedown", this.fooCell);
        },
        sendCell(name){
            this.$emit('cellClick',name)
        },
        sortClick(data,type,index){
            this.tableColumn.forEach(item=>{
                if(item!=data&&item.hasOwnProperty('order')){
                    item.order=''
                }
            })
            let orderStr=''
            
            this.setOrderStyle(type,index,data.order!==type)
            if(data.order==type){
                data.order=''
                orderStr=''
            }else{
                data.order=type
                orderStr=data.prop+','+type
            }
            this.$emit('setOrder',orderStr)
        },
        setOrderStyle(type,index,isStyle){
            let doms=document.getElementsByClassName(type+'-'+index)
            let orderDoms=document.getElementsByClassName('order-btn')
            for (let i = 0; i < orderDoms.length; i++) {
                orderDoms[i].style.color='#606266'
            }
            if(doms.length>0&&isStyle){
                doms[0].style.color='#4b96ff'
            }
        },
        //列拖拽
        columnDrop() {
        this.$nextTick(() => {
        const $table = this.$refs[this.tableRef]
        this.sortable2 = Sortable.create($table.$el.querySelector('.body--wrapper>.vxe-table--header .vxe-header--row'), {
            handle: '.vxe-header--column:not(.col--fixed)',
            onEnd: ({ item, newIndex, oldIndex }) => {
            const { collectColumn} = $table.getTableColumn()
            const targetThElem = item
            const wrapperElem = targetThElem.parentNode
            const newColumn = collectColumn[newIndex]
            if (newColumn.fixed) {
                // 错误的移动
                if (newIndex > oldIndex) {
                wrapperElem.insertBefore(targetThElem, wrapperElem.children[oldIndex])
                } else {
                wrapperElem.insertBefore(wrapperElem.children[oldIndex], targetThElem)
                }
                return this.$XModal.message({ content: '固定列不允许拖动！', status: 'error' })
            }
            // 转换真实索引
            const oldColumnIndex = $table.getColumnIndex(collectColumn[oldIndex])
            const newColumnIndex = $table.getColumnIndex(collectColumn[newIndex])
            // 移动到目标列
            const currRow = collectColumn.splice(oldColumnIndex, 1)[0]
            collectColumn.splice(newColumnIndex, 0, currRow)
            $table.loadColumn(collectColumn)
            let dragHeaderCopy=this.tableColumnCopy[oldColumnIndex]
            let oldI = this.tableColumn.findIndex(
                (item) => item.prop == dragHeaderCopy.prop
            );
            let newI=0
            if(newColumnIndex>oldI){ //从左向右拉
                newI=this.tableColumn.findIndex(
                    (item) => item.prop == this.tableColumnCopy[newColumnIndex].prop
                    );
            }else{
                newI=this.tableColumn.findIndex(
                    (item) => item.prop == this.tableColumnCopy[newColumnIndex-1].prop
                    );
            }
            this.tableColumn.splice(oldI, 1); //把当前拖动的表头去掉
            
            if(newColumnIndex>oldI){ //从左向右拉
                this.tableColumn.splice(newI, 0, dragHeaderCopy);
            }else{
                this.tableColumn.splice(newI+1, 0, dragHeaderCopy);
            }
            this.tableColumnCopy = JSON.parse(JSON.stringify(this.tableColumn)).filter((item) => {
                return item.checked||!item.hasOwnProperty('checked');
            });
            this.key += 1;
            this.$nextTick(()=>{
                this.columnDrop()
            })
            }
        })
        })
        },
        footerMethod () {
            // 返回一个二维数组的表尾合计
            return this.footerData
        }
    }
};
</script>

<style scoped lang="less">
.tableBox {
  height:100%;
    display: flex;
    overflow: hidden;
    /deep/ .noOrder {
      .vxe-cell .vxe-cell--title{
        padding-right: 0px !important;
      }
    }
    /deep/ .vxe-header--column ,/deep/ .vxe-body--column ,/deep/ .vxe-footer--column{
        height: 22px;
        padding: 4px 0;
        color: #000;
        .vxe-cell{
          justify-content: center;
          gap: 5px;
          text-align: center;
          .vxe-cell--title{
            position: relative;
            padding-right: 20px;
            .custom-sort{
              position: absolute;
              top: 1px;
              right: 0;
              display: flex;
              flex-direction: column;
              margin-bottom: 3px;
              cursor: pointer;
              min-width: 10px;
              float: right;
              margin-left: 5px;
              i{
                  height: 8px;
                  font-size: 12px;
              }
            }  
          }
        }
        // .col--ellipsis .vxe-cell{
        //     justify-content: center;
        //     gap: 5px;
        // }

    }
    /deep/ .col--checkbox .vxe-cell .vxe-cell--title{
        padding-right: 0;
    }
    /deep/ .vxe-header--column {
        background-color: #F0F4FE;
    }
    /deep/ .vxe-body--column{
        height: 38px;
        padding: 0;
        padding-bottom: 2px;
    }
    /deep/ .vxe-table--render-default .vxe-body--row.row--stripe {
        background-color: #EBEEF3;
    }
    /deep/ .vxe-table--render-default .vxe-body--row.row--current {
        background-color: #e6f7ff;
    }
    /deep/ .col--checkbox .vxe-cell{
        width: 100% !important;
        text-align: center;
    }
    /deep/ .vxe-cell span{
        overflow: hidden;
        text-overflow: ellipsis;
    }   
    /deep/.vxe-header--column.col--ellipsis>.vxe-cell .vxe-cell--title{
        cursor: move;
    }
    /deep/ .vxe-checkbox--label{
        padding: 0;
    }
    /deep/.vxe-table--render-default .vxe-body--column.col--ellipsis>.vxe-cell{
        max-height: unset !important;
    }
}
</style>